#include "gate_connector_impl.h"
#include "gate_client_session.h"
#include "EndianCast.h"

namespace utility
{
namespace network
{
gate_connector_impl::gate_connector_impl(net_module * netmodule) :
    event_handler_(this)
{
    if (netmodule)
    {
        connector_ = netmodule->create_connector();
        event_handler_.set_connector(connector_);
        connector_->set_event_handler(&event_handler_);
    }
    session_mgr_ = NULL;
}


gate_connector_impl::~gate_connector_impl(void)
{
    event_handler_.set_connector(NULL);
    connector_->set_event_handler(NULL);
}

bool gate_connector_impl::initialize(session_mgr * mgr)
{
    session_mgr_ = mgr;
    return session_mgr_ != NULL;
}

bool gate_connector_impl::connect_listener(const char * ip_address, const char * port)
{
    if (connector_)
    {
        try{
            connector_->connect(ip_address, port);
            return true;
        }
        catch(...)
        {
            return false;
        }
    }
    return false;
}

bool gate_connector_impl::connect(uint32 client_ip, uint16 client_port)
{
    if (_get_session())
    {
        gate_protocol_header header;
        header.op_type = CONNECT_REQ;
        header.source_ip = client_ip;
        header.source_port = client_port;
        header.destination_ip = _get_session()->get_remote_ip();
        _get_session()->send(&header, sizeof(header));
        return true;
    }

    return false;
}

session * gate_connector_impl::_get_session()
{
    if (connector_)
        return connector_->get_session();
    return NULL;
}

session_mgr * gate_connector_impl::get_session_mgr()
{
    return session_mgr_;
}

}
}


